package com.sparrow.manage.menu;

import com.sparrow.manage.common.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu, String> implements MenuService {

    @Autowired
    private MenuDao menuDao;

    @Override
    public List<Menu> queryTree() {
        List<Menu> menus = menuDao.findAll();   // 该方法返回值不会为null

        List<Menu> tree = new ArrayList<Menu>();

        Iterator<Menu> iterator = menus.iterator();
        while(iterator.hasNext()){
            Menu next = iterator.next();
            if(StringUtils.isBlank(next.getpId())){
                tree.add(next);
                iterator.remove();
            }
        }

        for(Menu menu : tree){
            generateTree(menu, menus);
        }

        return tree;
    }

    @Override
    protected JpaRepository<Menu, String> getDao() {
        return this.menuDao;
    }

    /**
     * 递归删除
     * 删除包括子类的所有菜单
     * @param id
     */
    @Override
    public void delete(String id) {
        List<Menu> menus = menuDao.queryBypId(id);
        if(menus != null || !menus.isEmpty()){
            for(Menu menu : menus){
                delete(menu.getId());
            }
        }
        menuDao.delete(id);
    }

    private void generateTree(Menu root, List<Menu> all){
        Iterator<Menu> iterator = all.iterator();
        while(iterator.hasNext()){
            Menu next = iterator.next();
            if(root.getId().equals(next.getpId())){
                if(root.getChildren() == null){
                    root.setChildren(new ArrayList<Menu>());
                }
                root.getChildren().add(next);
                iterator.remove();
            }
        }

        if(root.getChildren() != null){
            for(Menu menu : root.getChildren()){
                generateTree(menu, all);
            }
        }
    }
}
